import React from 'react';

import AMUIReact,{
    Pagination
} from 'amazeui-react';

class CKPages extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            count:this.calculatePages(this.props.count,this.props.number),
            current:this.props.current,
            data:{}
        };
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.count !== nextProps.count || this.props.current !== nextProps.current) {

            this.setState({
                count:this.calculatePages(nextProps.count,this.props.number),
                current:nextProps.current
            });
            this.countPages(nextProps.current,nextProps.count);
        }
    }

    componentDidMount() {
        this.countPages(this.state.current,this.state.count);
    }

    countPages(currentPage,countPage) {
        var pages = [];
        for (var i=0;i<countPage;i++) {
            let page = {
                title:i+1,
                link:i+1
            };
            if (currentPage === (i+1)) {
                page['active'] = true;
            }
            pages.push(page);
        }

        var data = {
            prevTitle: '上一页',
            prevLink: currentPage-1 > 1 ? currentPage-1 : 1,
            nextTitle: '下一页',
            nextLink: currentPage+1 > countPage ? countPage : currentPage+1,
            firstTitle: '第一页',
            firstLink: 1,
            lastTitle: '最末页',
            lastLink: countPage,
            pages: pages
        };

        this.setState({
            data:data
        });
    }

    selectHandler = (link, e)=>{
        e.preventDefault();
        console.log(link);
        this.props.onSelect(link);
    };

    calculatePages(count,number) {
        var pages;
        if (count % number == 0) {
            pages = parseInt(count/number);
        } else {
            pages = parseInt(count/number) + 1
        }
        return pages;
    }

    render() {
        return <Pagination right theme="default" onSelect={this.selectHandler} data={this.state.data}/>;
    }
}

CKPages.defaultProps = {
    current : 1,
    count   : 1,
    number  : 30,
    onSelect: function () {
    }
};

export default CKPages;

